package cn.lym.lucene.quickstart.search;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

/**
 * 提供检索的类
 * 
 * @author liuyimin
 *
 */
public class Searcher {
	/**
	 * logger
	 */
	private static final Logger logger = LogManager.getLogger(Searcher.class);

	/**
	 * 检索
	 * 
	 * @param indexDir
	 *            索引存放目录
	 * @param query
	 *            检索条件
	 * @param n
	 *            返回结果数量
	 * @return
	 * @throws Exception
	 */
	public List<Document> search(String indexDir, Query query, int n) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("Search " + indexDir + "　for　" + n + " documents, with query: " + query);
		}

		Directory directory = FSDirectory.open(new File(indexDir));
		IndexReader reader = DirectoryReader.open(directory);
		IndexSearcher searcher = new IndexSearcher(reader);

		TopDocs topDocs = searcher.search(query, n);
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;

		if (logger.isDebugEnabled()) {
			logger.debug("Totally " + scoreDocs.length + " documents hit.");
		}

		List<Document> documents = new ArrayList<>(scoreDocs.length);
		for (ScoreDoc scoreDoc : scoreDocs) {
			documents.add(searcher.doc(scoreDoc.doc));
		}
		return documents;
	}
}
